package com.pureut.system.service.impl;

import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.domain.MaterialAccessories;
import com.pureut.system.domain.MaterialCoding;
import com.pureut.system.domain.SysTheAlarm;
import com.pureut.system.domain.dto.MaterialAwmateriaDto;
import com.pureut.system.domain.dto.MaterialMqDto;
import com.pureut.system.domain.dto.ProjectRecursionDto;
import com.pureut.system.domain.vo.MaterialAccessoriesVo;
import com.pureut.system.domain.vo.MaterialAlarmVo;
import com.pureut.system.export.MaterialAccessoriesExport;
import com.pureut.system.mapper.MaterialAccessoriesMapper;
import com.pureut.system.mapper.MaterialBomHalfMapper;
import com.pureut.system.mapper.MaterialCodingMapper;
import com.pureut.system.mapper.SysTheAlarmMapper;
import com.pureut.system.service.IMaterialAccessoriesService;
import com.pureut.system.util.MaterialMqUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 辅料信息是是实现类
 * @Param
 * @Date 22-11-25
 * @Author hl
 **/
@Service
public class MaterialAccessoriesServiceImpl implements IMaterialAccessoriesService {
    @Resource
    private MaterialAccessoriesMapper materialAccessoriesMapper;

    @Resource
    private SysTheAlarmMapper sysTheAlarmMapper;

    @Resource
    private MaterialAwmateriaServiceImpl materialAwmateriaServiceImpl;

    @Resource
    private MaterialCodingMapper materialCodingMapper;

    @Resource
    private SysMidSplitServiceImpl sysMidSplitServiceImpl;

    //BomMapper
    @Resource
    private MaterialBomHalfMapper materialBomHalfMapper;


    /**
     * 查询辅料信息
     *
     * @param materialAccessories 辅料信息
     * @return 辅料信息集合
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<MaterialAwmateriaDto> selectAccessoriesList(MaterialAccessoriesVo materialAccessories) {
        List<SysDictData> netArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<MaterialAwmateriaDto> list =  materialAccessoriesMapper.selectAccessoriesList(materialAccessories);
        for (MaterialAwmateriaDto dto:
                list) {
            dto.setMaterialUnitDict(netMap.get(String.valueOf(dto.getMaterialUnit())));
            dto.setBomType("2");
            dto.setBomTypeDict("辅料");
        }
        return list;
    }

    /**
     * 新增辅料信息
     * @param materialAccessories 辅料信息
     * @return 辅料信息集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAccessories(MaterialAccessories materialAccessories) throws Exception{
        materialAccessories.setDeptId(SecurityUtils.getDeptId());
        materialAccessories.setMaterialCode(sysMidSplitServiceImpl.splitStr(materialCodingMapper.selectCodingTypeThe(materialAccessories.getMaterialType())));
        materialAccessories.setCreateBy(SecurityUtils.getUsername());
        int ins = materialAccessoriesMapper.insertAccessories(materialAccessories);
        if(ins>0) {

            if (materialAccessories.getAlarmCode() != null) {

                List<SysTheAlarm> list = materialAwmateriaServiceImpl.alarmConfiguration(materialAccessories.getAlarmCode());
                long op = materialAccessories.getMaterialId();
                String materialCode = materialAccessories.getMaterialCode();
                for (SysTheAlarm sysTheAlarm :
                        list) {

                    String roles = "";
                    for (int i = 0; i < sysTheAlarm.getRoleIds().size(); i++) {

                        roles = roles + sysTheAlarm.getRoleIds().get(i);
                        if (sysTheAlarm.getRoleIds().size()-1!=i){
                            roles = roles + ",";
                        }

                    }

                    sysTheAlarm.setAlarmRoleId(roles);

                    sysTheAlarm.setAlarmAssociatedId(op);
                    sysTheAlarm.setAlarmOfMaterial(2);
                    sysTheAlarm.setAlarmMaterialCode(materialCode);
                }
            if (list.size()!=0){
                ins = sysTheAlarmMapper.insertSysTheAlarm(list);
            }

        }
            if(ins==0){
                throw new SQLException("抛出异常");
            }
            MaterialMqDto mq = new MaterialMqDto();
            mq.setMaterialCode(materialAccessories.getMaterialCode());
            mq.setMaterialName(materialAccessories.getMaterialName());
            mq.setMaterialSpec(materialAccessories.getMaterialSpec());
            mq.setMaterialPlace(materialAccessories.getMaterialPlace());
            mq.setMaterialCategory(2);
            mq.setMaterialType(materialAccessories.getMaterialType());
            mq.setMaterialInspection(materialAccessories.getMaterialInspection());
            mq.setMaterialUnit(String.valueOf(materialAccessories.getMaterialUnit()));
            mq.setMaterialHair(materialAccessories.getMaterialHair());
            mq.setMaterialClosed(materialAccessories.getMaterialClosed());
            mq.setMaterialReminder(materialAccessories.getMaterialReminder());//复检提醒
            mq.setMaterialQuality(materialAccessories.getMaterialQuality());//保质期
            mq.setMaterialOverdue(materialAccessories.getMaterialOverdue());//过期提醒
            mq.setMaterialMinSecurity(materialAccessories.getMaterialMinSecurity());//最小安全库存
            MaterialMqUtil.materialMqSend(mq);
        }
        return ins;
    }

    /**
     * 删除辅料信息
     *
     * @param materialId 辅料信息ID
     * @return 辅料信息集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteAccessories(String materialId) throws Exception{
        String[] materialIdS = materialId.split(",");
        //同步删除辅料信息
        MaterialMqDto mq = new MaterialMqDto();
        List<String> materialIdList = Arrays.asList(materialId.split(","));
        String accessoriesStr = materialAccessoriesMapper.getAccessoriesById(materialIdList);
        mq.setMaterialCode(accessoriesStr);
        //删除标识
        mq.setMark(3);
        MaterialMqUtil.materialMqSendDelete(mq);


        int is = materialAccessoriesMapper.deleteAccessoriesById(materialIdS);
        if(is>0){
            sysTheAlarmMapper.deleteSysTheAlarmById(materialIdS);

           // if(is==0){
                //throw new SQLException("抛出异常");
           // }
        }
        return is;
    }

    /**
     * 查询单个辅料信息
     *
     * @param materialId 辅料信息ID
     * @return 辅料信息集合
     */
    @Override
    public MaterialAwmateriaDto selectAccessoriesById(long materialId) {
        MaterialAccessoriesVo materialAccessories = new MaterialAccessoriesVo();
        materialAccessories.setMaterialId(materialId);
        List<MaterialAwmateriaDto> list = materialAccessoriesMapper.selectAccessoriesList(materialAccessories);
        MaterialAwmateriaDto materialAwmateriaDto = new MaterialAwmateriaDto();
        materialAwmateriaDto = list.get(0);
        int alarmOfMaterial =2;
        List<SysTheAlarm> theList = sysTheAlarmMapper.selectSysTheAlarmList(materialId,alarmOfMaterial);
        MaterialAlarmVo materialAlarmVo = materialAwmateriaServiceImpl.alarmConfigtType(theList);
        materialAwmateriaDto.setAlarmCode(materialAlarmVo);
        return materialAwmateriaDto;
    }

    /**
     * 修改辅料信息
     *
     * @param materialAccessories 辅料信息
     * @return 辅料信息集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMaterialAccessoriesEdit(MaterialAccessories materialAccessories) throws Exception{
        int ors = materialAccessoriesMapper.updateMaterialAccessoriesEdit(materialAccessories);
        if(ors>0){
            MaterialMqDto mq = new MaterialMqDto();
            mq.setMaterialCode(materialAccessories.getMaterialCode());
            mq.setMaterialName(materialAccessories.getMaterialName());
            mq.setMaterialSpec(materialAccessories.getMaterialSpec());
            mq.setMaterialPlace(materialAccessories.getMaterialPlace());
            mq.setMaterialCategory(2);
            mq.setMaterialType(materialAccessories.getMaterialType());
            mq.setMaterialInspection(materialAccessories.getMaterialInspection());
            mq.setMaterialUnit(String.valueOf(materialAccessories.getMaterialUnit()));
            mq.setMaterialHair(materialAccessories.getMaterialHair());
            mq.setMaterialClosed(materialAccessories.getMaterialClosed());
            mq.setMaterialReminder(materialAccessories.getMaterialReminder());//复检提醒
            mq.setMaterialQuality(materialAccessories.getMaterialQuality());//保质期
            mq.setMaterialOverdue(materialAccessories.getMaterialOverdue());//过期提醒
            mq.setMaterialMinSecurity(materialAccessories.getMaterialMinSecurity());//最小安全库存
            MaterialMqUtil.materialMqSend(mq);

            long materialId =  materialAccessories.getMaterialId();
            String materialCode = materialAccessories.getMaterialCode();
            sysTheAlarmMapper.deleteSysTheAlarmOnById(materialId);
            if(ors>0){
                long sy = materialAccessories.getMaterialId();
                List<SysTheAlarm> list = materialAwmateriaServiceImpl.alarmConfiguration(materialAccessories.getAlarmCode());
                for (SysTheAlarm sysTheAlarm:
                        list) {

                    String roles = "";
                    for (int i = 0; i < sysTheAlarm.getRoleIds().size(); i++) {

                        roles = roles + sysTheAlarm.getRoleIds().get(i);
                        if (sysTheAlarm.getRoleIds().size()-1!=i){
                            roles = roles + ",";
                        }

                    }

                    sysTheAlarm.setAlarmRoleId(roles);

                    sysTheAlarm.setAlarmAssociatedId(sy);
                    sysTheAlarm.setAlarmOfMaterial(2);
                    sysTheAlarm.setAlarmMaterialCode(materialCode);
                }
                if (list.size()!=0){
                    ors = sysTheAlarmMapper.insertSysTheAlarm(list);
                }

                if(ors == 0){
                    throw new SQLException("抛出异常");
                }
            }else{
                throw new SQLException("抛出异常");
            }
            materialBomHalfMapper.updateBomInfo(materialAccessories.getMaterialName(),materialAccessories.getMaterialCode());
            materialBomHalfMapper.updateBomDetail(materialAccessories.getMaterialName(),materialAccessories.getMaterialCode());
        }
        return ors;
    }

    /**
     * 冻结/解冻
     *
     * @param materialAccessories 辅料信息
     * @return 辅料信息集合
     */
    @Override
    public int updateAccessoriesEditFreeze(MaterialAccessories materialAccessories) {
        return materialAccessoriesMapper.updateAccessoriesEditFreeze(materialAccessories);
    }

    /**
     * 辅料信息树结构
     *
     * @param
     * @return 辅料信息集合
     */
    @Override
    public List<ProjectRecursionDto> selectChildrenAccListThe() {
        return MaterialAwmateriaServiceImpl.buildMenuTree(materialAccessoriesMapper.selectChildrenAccListThe());
    }

    /**
     * 根据物料编号查询详情
     * @param materialCode
     * @return
     */
    @Override
    public MaterialAccessories selectAccessoriesMaterialCode(String materialCode) {
        return materialAccessoriesMapper.selectAccessoriesMaterialCode(materialCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importMouldData(List<MaterialAccessoriesExport> coCustomer) {
        if (StringUtils.isNull(coCustomer) || coCustomer.size() == 0) {
            throw new GlobalException("导入辅料信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        //原料单位
        List<SysDictData> levelArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> levelMap = levelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (MaterialAccessoriesExport mouldModelExport : coCustomer) {
            MaterialAccessories materialAccessories = new MaterialAccessories();
            try {
                if (mouldModelExport.getMaterialName() == null || mouldModelExport.getMaterialType() == null || mouldModelExport.getMaterialUnit() == null) {
                    throw new GlobalException("存在必填字段为空,请核实");
                }

                materialAccessories.setMaterialName(mouldModelExport.getMaterialName());

                //通过原料类别名称查出原料类别id
                MaterialCoding materialCoding = materialCodingMapper.getMaterilTypeId(mouldModelExport.getMaterialType());

                if (materialCoding==null){
                    throw new GlobalException("不存在该辅料类别导入失败");
                }
                materialAccessories.setMaterialSpec(mouldModelExport.getMaterialSpec());
                materialAccessories.setMaterialType((int) materialCoding.getCodingId());

                materialAccessories.setMaterialPlace(mouldModelExport.getMaterialPlace());
                materialAccessories.setSuppliersName(mouldModelExport.getMaterialSuppliers());
                if (mouldModelExport.getMaterialQuality()!=null) {
                    materialAccessories.setMaterialQuality(Integer.parseInt(mouldModelExport.getMaterialQuality()));
                }
                if (mouldModelExport.getMaterialOverdue()!=null){
                    materialAccessories.setMaterialOverdue(Integer.parseInt(mouldModelExport.getMaterialOverdue()));
                }
                if (mouldModelExport.getMaterialInspection()!=null){
                    materialAccessories.setMaterialInspection(Integer.parseInt(mouldModelExport.getMaterialInspection()));
                }
                if (mouldModelExport.getMaterialReminder()!=null){
                    materialAccessories.setMaterialReminder(Integer.parseInt(mouldModelExport.getMaterialReminder()));
                }
                if (mouldModelExport.getMaterialMinSecurity()!=null){
                    materialAccessories.setMaterialMinSecurity(Integer.parseInt(mouldModelExport.getMaterialMinSecurity()));
                }

                //原料单位
                for (Map.Entry<String, String> entry : levelMap.entrySet()) {
                    if (entry.getValue().equals(mouldModelExport.getMaterialUnit())) {
                        materialAccessories.setMaterialUnit(Integer.parseInt(entry.getKey()));
                        break;
                    }
                }

                //超收标志
                if ("开".equals(mouldModelExport.getMaterialClosed())){
                    materialAccessories.setMaterialClosed(1);
                }else{
                    materialAccessories.setMaterialClosed(2);
                }
                if ("开".equals(mouldModelExport.getMaterialHair())){
                    materialAccessories.setMaterialHair(1);
                }else{
                    materialAccessories.setMaterialHair(2);
                }

                //超发标志

                int i = insertAccessories(materialAccessories);
                if (i==0){
                    throw new GlobalException("导入失败");
                }

                successNum++;
                successMsg.append(successNum).append("、辅料信息 ").append(mouldModelExport.getMaterialName()).append(" 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、辅料名称 " + mouldModelExport.getMaterialName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new GlobalException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }

    /**
     * 根据物料编码查询详情(委外订单明细列表fegin调用)
     */
    @Override
    public MaterialAwmateriaDto getAccessoriesViewByMaterialCode(String materialCode) {
        return materialAccessoriesMapper.getAccessoriesViewByMaterialCode(materialCode);
    }
}
